package logic

import (
	"context"
	"fmt"
	"zhihu/models"
	"zhihu/pkg"

	"zhihu/zhihu_rpc/internal/svc"
	"zhihu/zhihu_rpc/zhihu_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *zhihu_rpc.LoginRequest) (*zhihu_rpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	var token string
	if in.Phone != "" {
		key := fmt.Sprintf("%s:phone:%s", "login", in.Phone)
		get, _ := models.RDB.Get(models.Ctx, key).Result()
		if in.Code != get {
			return nil, fmt.Errorf("验证码错误")
		}
		if models.DB.Where("user_phone = ?", in.Phone).Limit(1).Find(&user).Error != nil {
			return nil, fmt.Errorf("服务器繁忙")
		}
		if user.ID == 0 {
			return nil, fmt.Errorf("该手机号未绑定账号")
		}
		token, _ = pkg.TokenHandler(fmt.Sprintf("%d", user.ID))
	} else {
		if models.DB.Where("user_account = ?", in.Account).Limit(1).Find(&user).Error != nil {
			return nil, fmt.Errorf("服务器繁忙")
		}
		if user.ID == 0 {
			return nil, fmt.Errorf("账号不存在")
		}
		if user.UserPassword != pkg.MD5(in.Password) {
			return nil, fmt.Errorf("账号或密码错误")
		}
		token, _ = pkg.TokenHandler(fmt.Sprintf("%d", user.ID))
	}
	return &zhihu_rpc.LoginResponse{
		Token: token,
	}, nil
}
